﻿namespace CraftingCode.SymbolicCalculator
{
    using System.Collections.Generic;

    public class Tokenizer
    {
        private readonly List<TokenizationRule> rules;

        public Tokenizer(IEnumerable<TokenizationRule> rules)
        {
            this.rules = new List<TokenizationRule>(rules);
        }

        public Tokenizer()
            : this(MathematicalExpressionParsingRules)
        {
        }

        private static IEnumerable<TokenizationRule> MathematicalExpressionParsingRules
        {
            get
            {               
                return new TokenizationRule[] { new AdditionTokenizationRule(), new LiteralTokenizationRule() };
            }
        }

        public IList<Token> TokenizeExpression(string expression)
        {
            var tokens = new List<Token>();
            while (expression.HasContent())
            {
                var token = CreateNextToken(expression);
                tokens.Add(token);
                expression = expression.RemoveFirstInstanceOf(token);
            }

            return tokens;
        }

        private Token CreateNextToken(string expression)
        {
            foreach (var rule in rules)
            {
                if (rule.CanCreateNextTokenIn(expression))
                {
                    return rule.CreateNextTokenIn(expression);
                }
            }

            throw new UnknownTokenException(expression);
        }
    }
}